import TRTC from 'trtc-wx-sdk'

Component({
  properties: {
    config: {
      type: Object,
      value: {}
    }
  },

  data: {
    pusher: null,
    playerList: [],
  },
  lifetimes:{
    ready() {
      this.TRTC = new TRTC(this)
      this.bindTRTCRoomEvent()
      this.init()
    },
    detached: function () {
    },
  },
  
  methods: {
    openSetting() {
      return new Promise((resolve, reject) => {
        wx.showModal({
          title: '温馨提示',
          content: '请授权微信小程序麦克风与摄像头权限，以使用视频功能',
          success: (res) => {
            if (res.confirm) {
              wx.openSetting({
                success: function (res) {
                  console.log('打开权限设置页面', res)
                  // const authSettingObj = res.authSetting
                  return resolve(true)
                },
              })
            } else {
              return reject()
            }
          },
          fail: (err) => {
            return reject()
          },
        })
      })
    },
    checkPermisson() {
      return new Promise((resolve, reject) => {
        wx.getSetting({
          success: async (res) => {
            const authSettingObj = res.authSetting
            console.log(authSettingObj)
            if (authSettingObj['scope.camera'] === true && authSettingObj['scope.record'] === true) {
              // 当前已经有权限了
              console.log('当前已经有视频录音权限了')
              return resolve(true)
            } else if (authSettingObj['scope.camera'] === false || authSettingObj['scope.record'] === false) {
              // 之前问过权限，但是拒绝了
              console.log('之前问过权限，但是拒绝了')
              // 打开setting
              await this.openSetting()
              try {
                return resolve(true)
              } catch {
                return reject(false)
              }
            } else {
              // 还没问过权限
              console.log('还没问过权限')
              // 去请求授权
              wx.authorize({
                success: (res) => {
                  return resolve(true)
                },
                fail: async (err) => {
                  // 拒绝授权了
                  // 打开setting
                  try {
                    await this.openSetting()
                    return resolve(true)
                  } catch {
                    return reject(false)
                  }
                },
              })
            }
          },
        })
      })
    },

    /* 实时音视频操作 */
    init(options) {
      // pusher 初始化参数
      const pusherConfig = {
        beautyLevel: 9,
        audioVolumeType: 'media',
      }
      this.TRTC.createPusher(pusherConfig)
      let {appId, room, sig, userId} = this.properties.config
      this.setData({
        pusher: this.TRTC.enterRoom({
          sdkAppID: appId, // 您的腾讯云账号
          userID: userId, //当前进房用户的userID
          userSig: sig, // 您服务端生成的userSig
          roomID: Number(room), // 您进房的房间号，
          enableMic: true, // 进房默认开启音频上行
          enableCamera: true, // 进房默认开启视频上行
        })
      }, async () => {
          this.TRTC.getPusherInstance().start() // 开始进行推流
          console.log('pusher:', this.data.pusher)
          // await this.checkPermisson()
      })
    },
    exitRoom() {
      const result = this.TRTC.exitRoom()
      this.setData({
        pusher: result.pusher,
        playerList: result.playerList,
      })
    },

    // 设置 pusher 属性
    setPusherAttributesHandler(options) {
      this.setData({
        pusher: this.TRTC.setPusherAttributes(options),
      })
    },
  
    // 设置某个 player 属性
    setPlayerAttributesHandler(player, options) {
      this.setData({
        playerList: this.TRTC.setPlayerAttributes(player.streamID, options),
      })
    },
  
    // 事件监听
    bindTRTCRoomEvent() {
      const TRTC_EVENT = this.TRTC.EVENT
      // 初始化事件订阅
      this.TRTC.on(TRTC_EVENT.LOCAL_JOIN, (event) => {
        console.log('* room LOCAL_JOIN', event)
        // // 进房成功，触发该事件后可以对本地视频和音频进行设置
        this.setPusherAttributesHandler({ enableCamera: true })
        this.setPusherAttributesHandler({ enableMic: true })
      })
      this.TRTC.on(TRTC_EVENT.LOCAL_LEAVE, (event) => {
        console.log('* room LOCAL_LEAVE', event)
      })
      this.TRTC.on(TRTC_EVENT.ERROR, (event) => {
        console.log('* room ERROR', event)
      })
      // 远端用户退出
      this.TRTC.on(TRTC_EVENT.REMOTE_USER_LEAVE, (event) => {
        const { playerList } = event.data
        this.setData({
          playerList: playerList
        })
        console.log('* room REMOTE_USER_LEAVE', event)
      })
      // 远端用户推送视频
      this.TRTC.on(TRTC_EVENT.REMOTE_VIDEO_ADD, (event) => {
        console.log('* room REMOTE_VIDEO_ADD',  event)
        const { player } = event.data
        // 开始播放远端的视频流，默认是不播放的
        this.setPlayerAttributesHandler(player, { muteVideo: false })
      })
      // 远端用户取消推送视频
      this.TRTC.on(TRTC_EVENT.REMOTE_VIDEO_REMOVE, (event) => {
        console.log('* room REMOTE_VIDEO_REMOVE', event)
        const { player } = event.data
        this.setPlayerAttributesHandler(player, { muteVideo: true })
      })
      // 远端用户推送音频
      this.TRTC.on(TRTC_EVENT.REMOTE_AUDIO_ADD, (event) => {
        console.log('* room REMOTE_AUDIO_ADD', event)
        const { player } = event.data
        this.setPlayerAttributesHandler(player, { muteAudio: false })
      })
      // 远端用户取消推送音频
      this.TRTC.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, (event) => {
        console.log('* room REMOTE_AUDIO_REMOVE', event)
        const { player } = event.data
        this.setPlayerAttributesHandler(player, { muteAudio: true })
      })
    },

    // 是否订阅某一个player Audio
    _mutePlayerAudio(event) {
      const player = event.currentTarget.dataset.value
      if (player.hasAudio && player.muteAudio) {
        this.setPlayerAttributesHandler(player, { muteAudio: false })
        return
      }
      if (player.hasAudio && !player.muteAudio) {
        this.setPlayerAttributesHandler(player, { muteAudio: true })
        return
      }
    },
  

    // 订阅 / 取消订阅某一个player Video
    _mutePlayerVideo(event) {
      const player = event.currentTarget.dataset.value
      if (player.hasVideo && player.muteVideo) {
        this.setPlayerAttributesHandler(player, { muteVideo: false })
        return
      }
      if (player.hasVideo && !player.muteVideo) {
        this.setPlayerAttributesHandler(player, { muteVideo: true })
        return
      }
    },
    _pusherSwitchCamera() {
      const  frontCamera = this.data.pusher.frontCamera === 'front' ? 'back' : 'front'
      this.TRTC.getPusherInstance().switchCamera(frontCamera)
    },
  
    _setPlayerSoundMode() {
      if (this.data.playerList.length === 0) {
        return
      }
      const player = this.TRTC.getPlayerList()
      const soundMode = player[0].soundMode === 'speaker' ? 'ear' : 'speaker'
      this.setPlayerAttributesHandler(player[0], { soundMode })
    },
    // 请保持跟 wxml 中绑定的事件名称一致
    _pusherStateChangeHandler(event) {
      this.TRTC.pusherEventHandler(event)
    },
    _pusherNetStatusHandler(event) {
      this.TRTC.pusherNetStatusHandler(event)
    },
    _pusherErrorHandler(event) {
      this.TRTC.pusherErrorHandler(event)
    },
    _pusherBGMStartHandler(event) {
      this.TRTC.pusherBGMStartHandler(event)
    },
    _pusherBGMProgressHandler(event) {
      this.TRTC.pusherBGMProgressHandler(event)
    },
    _pusherBGMCompleteHandler(event) {
      this.TRTC.pusherBGMCompleteHandler(event)
    },
    _pusherAudioVolumeNotify(event) {
      this.TRTC.pusherAudioVolumeNotify(event)
    },
    _playerStateChange(event) {
      this.TRTC.playerEventHandler(event)
    },
    _playerFullscreenChange(event) {
      this.TRTC.playerFullscreenChange(event)
    },
    _playerNetStatus(event) {
      this.TRTC.playerNetStatus(event)
    },
    _playerAudioVolumeNotify(event) {
      this.TRTC.playerAudioVolumeNotify(event)
    },
  }
})
